<?php
namespace app\h5api\controller;

use app\common\service\Wechat;
use app\common\model\User;
use plug\SUtil;

class Login extends Base
{
    /**
     * @route('h5/Authorize','post')
     * 获取公众号授权链接
     */
	public function Authorize(){
		$url = input('post.url');
		$this->result(Wechat::GetAuthorizeUrl($url),1,'操作成功');
	}

	/**
	 * @route('h5/abc')
	 * 获取公众号授权链接
	 */
	public function abc(){
		$code = input('get.code');
		echo $code;die;
	}

	/**
	 * @route('h5/Authlogin','post')
	 * 通过 code 换取网页授权信息
	 */
	public function Authlogin() {
		$code = input('post.code');
		if(!$code){
			$this->result([],-1,'404');
		}
		
		//通过 code 换取网页授权access_token和openid
		//这里通过 code 换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同
		$AuthorizeInfo = Wechat::AuthorizeInfo($code);
		if(!$AuthorizeInfo){
			$this->result([],-1,'404');
		}
//		print_r($AuthorizeInfo);
        //获取用户基本信息（包括UnionID机制）
        $UserInfo = Wechat::userinfo($AuthorizeInfo['access_token'],$AuthorizeInfo['openid']);

		$userModel = new User();
		$user = $userModel->UnionidGetUser($AuthorizeInfo['unionid']);
		//查询该用户是否注册过
		if(!$user){//如果没注册过
			//新增用户
			$id = $userModel->binduser($UserInfo['nickname'],$UserInfo['sex'],$UserInfo['headimgurl'],$UserInfo['openid'],$UserInfo['unionid']);
			if(!$id){
				$this->result([],-1,'404');
			}
			//生成授权token
			$token = SUtil::createjwt(['time'=>time(),'user_id'=>$id,'nick_name'=>$UserInfo['nickname']]);
			return $this->result(['token'=>$token],1,'授权成功');
		}

		$res = $userModel->login($user['user_id'],$UserInfo['openid'],'wx_openid');
		if(!$res){
			$this->result([],-1,'404');
		}
		$token = SUtil::createjwt(['time'=>time(),'user_id'=>$user['user_id'],'nick_name'=>$user['nick_name'],'type'=>'online']);
		return $this->result(['token'=>$token],1,'授权成功');
	}

    /**
     * @route('h5/wxAppLogin','post')
     * 微信小程序直接登录
     */
    public function wxAppLogin()
    {
//		$token = SUtil::createjwt(['time'=>time(),'user_id'=>331,'nick_name'=>'肥肥的考拉']);
//		return $this->result(['token'=>$token],1,'授权成功');

        //登录时获取的 code，可通过wx.login获取
        $code = input('post.code');
        //经过加密的activityId，解密后可得到原始的activityId。若解密后得到的 activityId 可以与开发者后台的活动 id 对应上则验证通过，否则表明 valid 字段不可靠（被篡改）
        $encryptedData = input('post.encryptedData');
        //加密算法的初始向量
        $iv = input('post.iv');
        $avatarUrl = input('post.avatarUrl');//用户头像
        $nick_name = input('post.nick_name');//用户昵称
        if (empty($code) || empty($encryptedData) || empty($iv) || empty($avatarUrl) || empty($nick_name)) {
            $this->result([],-1,'参数缺失123');
        }

        //登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见小程序登录。
        $tempJscode2session = Wechat::jscode2session($code);
        if (!$tempJscode2session) {
            $this->result([],-1,'请求微信错误');
        }

        $openid = $tempJscode2session["openid"];//用户唯一标识
        $session_key = $tempJscode2session["session_key"];//会话密钥
        $errCode = Wechat::decryptData($session_key,$encryptedData, $iv, $data);  //其中$data包含用户的所有数据
        if ($errCode != 0) {
            $this->result([],-1,"登录失败,错误码:".$errCode);
        }
        $data = json_decode($data, true);//获得用户信息
        isset($tempJscode2session['unionid'])?$unionid = $tempJscode2session['unionid']:$unionid = '';
//        var_dump($data);die;
        $userModel = new User();
        $user = $userModel->UnionidGetUser($unionid);
        //查询该用户是否注册过
        if(!$user){//如果没注册过
            //新增用户
            $id = $userModel->binduser($nick_name,$data['gender'],$avatarUrl,$openid,$unionid,'applets_openid');
            if(!$id){
                $this->result([],-1,'404');
            }
            //生成授权token
            $token = SUtil::createjwt(['time'=>time(),'user_id'=>$id,'nick_name'=>$nick_name]);
            return $this->result(['token'=>$token],1,'授权成功');
        }
        $res = $userModel->login($user['user_id'],$openid,'applets_openid');
        if(!$res){
            $this->result([],-1,'404');
        }
        $token = SUtil::createjwt(['time'=>time(),'user_id'=>$user['user_id'],'nick_name'=>$user['nick_name'],'type'=>'online']);
        return $this->result(['token'=>$token],1,'授权成功');
    }
}
